<!--
 * @description  : 中小学坐标采集-新增编辑
 * @descriptionDetail : 中小学坐标采集-新增编辑
 * @author       : bln
 * @create       : 2024-09-02 00:00:00
-->
<template>
	<view class="page">
		<!-- #ifdef H5-ONLY -->
		<theme-navbar :is-white="false" :title="title" :custom-back="goBack" style="z-index: 99999"></theme-navbar>
		<!-- #endif -->
		<view class="content content-bg ifn-content" style="background-color: white">
			<form-section title="基本信息"></form-section>
			<u-form :model="schoolForm" :rules="rules" :errorType="['border-bottom', 'message']"
				style="padding: 0px 15px;" ref="uForm">
				<u-form-item label="所属组织名称" :label-width="labelWidth" prop="orgName" required>
					<u-input input-align="right" :custom-style="valueStyle" v-model="schoolForm.orgName"
						:clearable="false" readOnly />
				</u-form-item>
				<u-form-item label="所属网格" :label-width="labelWidth" prop="gridName" required>
					<u-input input-align="right" placeholder="请选择所属网格" :custom-style="valueStyle"
						v-model="schoolForm.gridName" :clearable="false" readOnly @click="selectGrid" />
				</u-form-item>
				<u-form-item label="区域名称" :label-width="labelWidth" prop="prohibitName" required>
					<u-input input-align="right" placeholder="请输入区域名称" :custom-style="valueStyle"
						v-model="schoolForm.prohibitName" />
				</u-form-item>
				<u-form-item label="区域类型" :label-width="labelWidth" prop="prohibitClassifyName" required>
					<u-input input-align="right" :disabled="true" v-model="schoolForm.prohibitClassifyName"
						type="select" placeholder="请选择" @click="prohibitClassifyShow = true" />
					<u-select v-model="prohibitClassifyShow" mode="single-column" :list="prohibitClassifyList"
						@confirm="prohibitClassifyConfirm"></u-select>
				</u-form-item>
				<u-form-item label="负责人" :label-width="labelWidth" prop="prohibitHead">
					<u-input input-align="right" placeholder="请输入负责人" :custom-style="valueStyle"
						v-model="schoolForm.prohibitHead" />
				</u-form-item>
				<u-form-item label="联系电话" :label-width="labelWidth" prop="prohibitTel">
					<u-input input-align="right" placeholder="请输入联系电话" :custom-style="valueStyle"
						v-model="schoolForm.prohibitTel" />
				</u-form-item>
				<u-form-item label="地址" :label-width="labelWidth" prop="prohibitAddr" required>
					<u-input input-align="right" placeholder="请输入地址" :custom-style="valueStyle"
						v-model="schoolForm.prohibitAddr" />
				</u-form-item>
				<u-form-item label-width="190" label="状态" prop="isActive" required>
					<u-switch slot="right" v-model="schoolForm.isActive"
						@change="switchChange($event,'isActive')"></u-switch>
				</u-form-item>
				<u-form-item :label-position="labelPosition" label="区域情况描述" prop="prohibitDesc" required>
					<u-input type="textarea" height="100" :auto-height="true" placeholder="请输入区域情况描述"
						v-model="schoolForm.prohibitDesc" />
				</u-form-item>
			</u-form>
			<u-gap :marginRight="getGapMarginRowNumber()" :marginLeft="getGapMarginRowNumber()"
				:height="$theme.cm_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
		</view>
		<view :class="['list-content', coordinatesList.length ? '' : 'list-bg-w']">
			<view class="u-flex u-row-between u-p-l-36 u-p-r-36" style="background-color: white">
				<view class="u-flex">
					<form-section title="出入口信息" :customStyle="{ width: 'auto' }"></form-section>
					<span class="u-m-l-10" :style="{ color: '#717579',fontSize: '14px' }">(向左滑动编辑/删除)</span>
				</view>
				<view class="u-flex" @click="addPoints">
					<u-icon class="u-m-l-30 u-m-l-10" name="plus-circle" color="primary" size="40" />
					<span :style="{ color: '#1890ff' }">新增</span>
				</view>
			</view>
			<view class="list-item-root" v-for="item in coordinatesList" :key="item.positionUuid">
				<u-swipe-action :index="item.positionUuid" :show="item.show" :options="options" @open="swiperOpen"
					@click="swiperClick">
					<view class="list-lay">
						<view class="content-title-lay">
							<text>坐标名称：{{ item.pointName || '' }}</text>
						</view>
						<view class="content-title-lay">
							<text>位置类型：{{ item.positionTypeName || '' }}</text>
						</view>
						<view class="content-title-lay">
							<text>经纬度（点坐标）：{{ item.coordinates }}</text>
						</view>
					</view>
				</u-swipe-action>
			</view>
		</view>
		<view class="submit-btns btn-other-cls">
			<u-button class="u-btn" type="primary" :loading="submitBtnLoading" @click="handlerDoSubmit()">提交</u-button>
		</view>
		<!-- 数据字典 -->
		<dic-choice :keyWord="dicKeyWords" :currentSelect="dicCurrentSelect" v-model="dicShow"
			@confirm="selectDicConfirm"></dic-choice>
	</view>
</template>
<script>
	import DicInput from '@/components/dic_input.vue'
	import DicChoice from '@/components/dic_choice.vue'
	import FormSection from '@/components/form-section.vue'
	import queryService from '@/service/query/query.service.js'
	import MescrollMoreMixin from '@/components/mescroll-uni/mixins/mescroll-more.js'

	export default {
		mixins: [MescrollMoreMixin],
		components: {
			DicChoice,
			DicInput,
			FormSection
		},
		data() {
			return {
				dicShow: false,
				submitBtnLoading: false,
				prohibitClassifyShow: false,
				title: '添加中小学',
				pointTitle: '添加出入口信息',
				handlerType: 'add',
				labelWidth: '200',
				labelPosition: 'top',
				schoolForm: {},
				dicKeyWords: '',
				dicCurrentSelect: '',
				coordinatesList: [],
				rules: {
					gridName: [{
						required: true,
						message: '请选择所属网格',
						trigger: ['change']
					}],
					prohibitName: [{
						required: true,
						message: '请输入区域名称',
						trigger: ['change', 'blur']
					}],
					prohibitClassifyName: [{
						required: true,
						message: '请选择区域类型',
						trigger: ['change', 'blur']
					}],
					prohibitAddr: [{
						required: true,
						message: '请输入地址',
						trigger: ['change', 'blur']
					}],
					prohibitDesc: [{
						required: true,
						message: '请输入区域情况描述',
						trigger: ['change', 'blur']
					},
					{
						max: 100,
						message: '区域情况描述长度请输入100个字符之间！',
						trigger: ['change', 'blur']
					},
					],
					prohibitTel: [{
						validator: () => {
							if (this.schoolForm.prohibitTel) {
								return this.$u.test.mobile(this.schoolForm.prohibitTel)
							} else {
								return true
							}
						},
						message: '手机号码不正确',
						trigger: ['change', 'blur']
					}]
				},
				positionTypeList: [{
						value: '1',
						label: '中心点'
					},
					{
						value: '3',
						label: '出入口'
					}
				],
				prohibitClassifyList: [{
						value: '0101',
						label: '幼儿园'
					},
					{
						value: '0102',
						label: '中小学'
					}
				],
				options: [{
						text: '编辑',
						style: {
							backgroundColor: '#007aff'
						}
					},
					{
						text: '删除',
						style: {
							backgroundColor: '#dd524d'
						}
					}
				],
				valueStyle: {
					marginRight: '5px'
				},
				userInfo: this.$store.state.userInfo
			}
		},
		onReady() {
			this.$refs.uForm && this.$refs.uForm.setRules(this.rules)
		},
		onLoad(opt) {
			this.handlerType = opt.type
			if (opt.type === 'edit') {
				this.title = '编辑中小学'
				this.schoolForm.gridName = opt.gridName
				this.getProhibitDetail(opt.prohibitUuid)
			} else {
				this.title = '添加中小学'
				this.schoolForm.isActive = true;
				this.schoolForm.prohibitUuid = this.thirtyTwoID()
			}
			this.schoolForm.orgName = this.userInfo.orgName
			this.schoolForm.ownOrgUuid = this.userInfo.orgUuid
		},
		methods: {
			// 获取详情
			getProhibitDetail(id) {
				this.$u.loading('正在加载...')
				queryService.coordinate4School.getProhibitInfo({
					prohibitUuid: id
				}).then(res => {
					this.$u.hideLoading()
					if (res.success) {
						this.schoolForm = Object.assign({}, this.schoolForm, res.bean)
						this.schoolForm.isActive = this.schoolForm.isActive == 1 ? true : false;
						this.schoolForm.prohibitClassifyName = this.prohibitClassifyList.find(p => p.value === res
							.bean.prohibitClassifyCode)?.label || ''
						if (this.schoolForm.prohibitPositionsList) {
							this.coordinatesList = this.schoolForm.prohibitPositionsList.map(v => {
								const point = JSON.parse(v.pointCoordinatesJson)
								return {
									...v,
									show: false,
									coordinates: point.coordinates.join(),
									positionTypeName: this.positionTypeList.find(p => p.value === v.positionType)?.label || ''
								}
							})
						}
					}
				}).catch(err => {
					this.$u.hideLoading()
					this.$u.toast(err)
				})
			},
			// 所属网格选择
			selectGrid() {
				if (this.handlerType === 'add') {
					this.$u.route({
						url: 'pages/query/coordinateForSchool/chooseGrid'
					})
				}
			},
			// 获取所属网格信息
			updateBackState(param) {
				const {gridInfo,pointInfo} = param
				if (gridInfo) {
					this.schoolForm.gridName = gridInfo.gridName || ''
					this.schoolForm.ownGridUuid = gridInfo.gridUuid || ''
					this.$forceUpdate()
				}
				if (pointInfo) {
					const {type,info} = pointInfo || {}
					if (type === 'add') {
						this.coordinatesList.push({...info,...{type:type,positionUuid:this.thirtyTwoID()}});
						console.log(this.coordinatesList)
					} else {
						this.coordinatesList = this.coordinatesList.map(item => {
							if (item.positionUuid === info.positionUuid) {
								item = {...item,...info}
							}
							return item
						})
					}
				}
			},
			// 区域类型选择
			prohibitClassifyConfirm(e) {
				this.schoolForm.prohibitClassifyCode = e[0].value
				this.schoolForm.prohibitClassifyName = e[0].label
			},
			// 状态字典展开
			dicSelectOpen(keyWords) {
				return this.dicKeyWords == keyWords && this.dicShow
			},
			// 状态字典显示
			showDic(key, cur) {
				if (this.dicShow) return
				this.dicKeyWords = key
				this.dicCurrentSelect = cur
				this.dicShow = true
			},
			// 状态字典选择确认
			selectDicConfirm(e) {
				if (this.dicKeyWords == this.$u.dic.DIC_KEYS.S_SYS_IS_ACTIVE) {
					this.schoolForm.isActiveName = e[0].label
					this.schoolForm.isActive = e[0].extra.bcbCode
				}
			},
			// gap间距
			getGapMarginRowNumber() {
				return '-' + this.$theme.cm_content_paddng_row.replace('rpx', '');
			},
			// 新增编辑出入口信息
			addPoints() {
				this.setRouteParam({
					type: 'add',
					pointInfo: {
						prohibitUuid: this.schoolForm.prohibitUuid
					}
				})
				this.$u.route({
					url: 'pages/query/coordinateForSchool/addCustomEntity'
				})
			},
			// 出入口滑动
			swiperClick(index1, index) {
				let cur = -1;
				for (let i = 0; i < this.coordinatesList.length; i++) {
				  if (this.coordinatesList[i].positionUuid === index1) {
				    cur = i;
				    break;
				  }
				}
				if (cur == -1) {
				  this.$u.toast("选中数据无效");
				  return;
				}
				let pointInfo = this.coordinatesList[cur];
				if (index === 0) {
					this.setRouteParam({
						type: 'edit',
						pointInfo
					})
					this.$u.route({
						url: 'pages/query/coordinateForSchool/addCustomEntity'
					})
				} else {
					if(pointInfo.type == 'add') {
						this.coordinatesList.splice(cur, 1)
					} else {
						this.deleteCoordinate(index1,cur)
					}
					
				}
				this.coordinatesList.map((val, idx) => {
					this.coordinatesList[idx].show = false
				})
			},
			// 出入口滑块展示
			swiperOpen(index) {
				this.coordinatesList.map((val, idx) => {
					this.coordinatesList[idx].show = index === val.positionUuid
				})
			},
			// 生成32位ID
			thirtyTwoID() {
				let len = len || 32
				let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
				let maxPos = chars.length
				let pwd = ''
				for (let i = 0; i < len; i++) {
					pwd += chars.charAt(Math.floor(Math.random() * maxPos))
				}
				return pwd
			},
			// 删除出入口信息
			deleteCoordinate(cItem, index) {
				queryService.coordinate4School.deleteProhibitPositions({
					positionUuid: cItem
				}).then(res => {
					if (res.success) {
						this.$u.toast('删除成功')
						this.coordinatesList.splice(index, 1)
					}
				})
			},
			// 提交
			handlerDoSubmit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.submitBtnLoading = true
						let list = JSON.parse(JSON.stringify(this.coordinatesList))
						list = list.map(item => {
							const coord = {
								type: 'Point',
								coordinates: [
									[item.coordinates.split(',')]
								]
							}
							if(item.type == 'add') {
								delete item.positionUuid
							}
							!!item.type && delete item.type;
							
							return {
								...item,
								pointCoordinatesJson: JSON.stringify(coord)
							}
						})
						queryService.coordinate4School.saveProhibitPositions(list).then(res => {
							if (res.success) {
								let parm = {...{},...this.schoolForm};
								// 将 isActive true false 转为后端
								parm.isActive = Number(parm.isActive)
								queryService.coordinate4School.saveProhibitInfo(parm).then(
									res => {
										if (res.success) {
											this.goRBack()
										} else {
											this.$u.toast(res.msg)
										}
										this.submitBtnLoading = false
									})
							} else {
								this.$u.toast(res.msg)
								this.submitBtnLoading = false
							}
						})
					}
				})
			},
			// switch开关
			switchChange(status, type) {
				this.schoolForm[type] = status;
			}
		}
	}
</script>
<style scoped lang="scss">
	.page {
		padding: 0;
	}

	.content {
		padding: 0 $cm-content-paddng-row;
	}

	.list-content {
		padding-bottom: 140rpx;
		background-color: #f3f4f5;
	}

	.list-bg-w {
		background-color: #fff;
	}

	.secion-title {
		font-size: 0.9rem;
		font-weight: 500;
		padding: 20rpx 0px 20rpx;
	}

	.title-select-tip {
		color: #c0c4cc;
	}

	.content-title-lay {
		padding: 5px 3px;
	}

	.list-item-root {
		margin: 10px;
		border-radius: 15px;
		overflow: hidden;
	}

	.list-lay {
		margin: 10px;
	}
</style>